/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.thu.laud.objectstore.fieldmanager;

import java.nio.ByteBuffer;
import java.util.Arrays;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.utils.ByteBufferUtil;
import cn.edu.thu.laud.utils.serde.ConverterContext;
import cn.edu.thu.laud.objectstore.index.BatchMutation;

/**
 * Object for writing collection columns
 * @author zhuoan
 *
 */
public class WriteMap extends ExternalEntityWriter {


	public WriteMap(Cassandra.Client client, ConverterContext context,
			String ownerColumnFamily, ByteBuffer rowKey, ByteBuffer ownerColumn) {
		super(client, context, ownerColumnFamily, rowKey, ownerColumn);
	}

	

	/**
	 * Write the relationship column
	 * @param mutator
	 */
	public void writeRelationship(BatchMutation mutator, Object key, Object entityKey) {
		// a DRE, take the property +256 bytes so the buffer hopefully won't need to be re-allocated and copied.
		ByteBuffer buffer = ByteBuffer.allocate(ownerColumn.remaining() + 256);
		byte[] ownerColBytes = ByteBufferUtil.getArray(ownerColumn);
		buffer.mark();
		buffer.put(ownerColBytes);
		buffer.put(DELIM_MIN);
		buffer = converterContext.getRowKeyForId(key, buffer);
		buffer.limit(buffer.position());
		buffer.reset();
		
		super.addStoredColumn(buffer);
		
		ByteBuffer value = converterContext.getRowKeyForId(entityKey, null);
		value.reset();

		Column keyColumn = new Column(buffer).setValue(value).setTimestamp(System.currentTimeMillis());

		mutator.addInsertion(rowKey, Arrays.asList(new String[]{ownerColumnFamily}), keyColumn);

	}
}
